package org.jxf.gps.jt808.nettysample.test;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jfk.core.utils.ByteUtils;
import org.jfk.core.utils.StringUtils;
import org.jxf.gps.jt808.message.MessageParser;

import com.csvreader.CsvReader;

public class Client {
	private static Logger logger = Logger.getLogger(Client.class);
	
	public static String host;
	public static int port;
	
	public void start() throws InterruptedException{
//		long mdn = 188000000000l;
//		for (int i = 0 ; i < 100 ; i++){
//			Thread.sleep(50);
//			mdn = mdn + 1;
//			new Thread(new SimTerm(Long.valueOf(mdn).toString())).start();
//		}
		new Thread(new SimTerm("018988888888")).start();
	}	
	public class SimTerm implements Runnable {
		
		private String mdn = "";
		
		public SimTerm(String mdn){
			this.mdn = mdn;
		}

		@Override
		public void run() {
			ChannelFactory factory = new NioClientSocketChannelFactory(Executors
					.newCachedThreadPool(), Executors.newCachedThreadPool());

			ClientBootstrap bootstrap = new ClientBootstrap(factory);
			ClientHandler handler = new ClientHandler();
			bootstrap.getPipeline().addLast("handler", handler);
			bootstrap.setOption("tcpNoDelay", true);
			bootstrap.setOption("keepAlive", true);

			ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(
					host, port));
			System.out.println("MDN = "+mdn);
			
			//车辆鄂Q01268在20150119000000至20150119081608时段轨迹导出
			//车辆鄂Q07777在20150119000000至20150119082249时段轨迹导出
			CsvReader r = null;
			try {
//				r = new CsvReader(
//						"C:\\Users\\Administrator\\Desktop\\trace\\车辆鄂Q00083在20150119000000至20150119081833时段轨迹导出.csv",
//						',', Charset.forName("GBK"));
				r = new CsvReader(
						"C:\\Users\\Administrator\\Desktop\\trace\\trace_2768.csv",
						',', Charset.forName("GBK"));

				r.readHeaders();
				int i = 0;
				// 逐条读取记录，直至读完
				while (r.readRecord() && i < 10000) {

					//System.out.println(ss);
					Thread.sleep(30000);
					String ss = getData(r,mdn);
					sendMsg(channelFuture,ss);
					i++;
					//System.out.println(i);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				r.close();
			}
			
		}
	}
	
	public static void main(String[] args) throws Exception {
		host = "127.0.0.1";// args[0];
		port = 59090;// Integer.parseInt(args[1]);

		Client client = new Client();
		client.start();
		
	}
	
	public static void sendMsg(ChannelFuture channelFuture ,String hexString) throws Exception{
		byte[] msgBuff = ByteUtils.hexStringToBytes(hexString);
		byte[] head_body = new byte[msgBuff.length - 3];
		System.arraycopy(msgBuff, 1, head_body, 0, head_body.length);
		byte crc = ByteUtils.genCRC16(head_body);
		msgBuff[msgBuff.length - 2] = crc;
		byte[] newBuff = MessageParser.convert7E7D(msgBuff);
		ChannelBuffer buf = ChannelBuffers.buffer(newBuff.length);
		buf.writeBytes(newBuff);
		//logger.info(ByteUtils.byteToHexString(newBuff));
		while (!channelFuture.getChannel().isConnected()){
			//避免异常：java.nio.channels.NotYetConnectedException
			Thread.sleep(100);
		}
		channelFuture.getChannel().write(buf);
	}
	
	public static String getData(CsvReader r,String mdn) throws Exception{
		// 读取一条记录
		// System.out.println(r.getRawRecord());
		// 按列名读取这条记录的值
		String wd_ = r.get("纬度");
		String jd_ = r.get("经度");
		String sd_ = r.get("速度");
		String sj_ = r.get("时间");
		String fx_ = r.get("方向");

		//String id = r.get("车机系统号");
		String id = mdn;
//                  7E0200002A0189888888880004000000000000180301CB998E068251210322029E001E15022518161501040001E848020200640302029E417E
//		            7E0200002A1000000000050006000000050087B94301CB998E068251210322029E001E14111117054601040001E848020200640302029ED47E
		String s = "7E0200002A0189888888880004000000000000180301CB998E068251210322029E001E15022518161501040001E848020200640302029E417E";
		String s0 = s.substring(0, 10);
		String s1 = s.substring(22, 42);
		String s2 = s.substring(82);
//		System.out.println(s0);
//		System.out.println(s1);
//		System.out.println(s2);


		double wd = Double.valueOf(wd_).doubleValue();
		//System.out.println(wd);
		wd = wd * 1000000;
		String _wd = ByteUtils.intToDWordString((int) wd);
		//System.out.println("wd = " + _wd);

		double jd = Double.valueOf(jd_).doubleValue();
		//System.out.println(jd);
		jd = jd * 1000000;
		String _jd = ByteUtils.intToDWordString((int) jd);
		//System.out.println("jd = " + _jd);

		int gc = Integer.valueOf("802").intValue();
		String _gc = ByteUtils.intToWordString(gc);
		//System.out.println("gc = " + _gc);

		float sd = Float.valueOf(sd_).floatValue() * 10;
		String _sd = ByteUtils.intToWordString((int)sd);
		//System.out.println("sd = " + _sd);

		
		/*
		int fx = Integer.valueOf("30").intValue();
		if ("北".equals(fx_)){
			fx = 0;
		}else if ("东北".equals(fx_)){
			fx = 45;
		}else if ("东".equals(fx_)){
			fx = 90;
		}else if ("东南".equals(fx_)){
			fx = 135;
		}else if ("南".equals(fx_)){
			fx = 180;
		}else if ("西南".equals(fx_)){
			fx = 225;
		}else if ("西".equals(fx_)){
			fx = 270;
		}else if ("西北".equals(fx_)){
			fx = 315;
		}else{
			fx = 0;
		}
		*/
		int fx = Integer.valueOf(fx_);
		String _fx = ByteUtils.intToWordString(fx);
		//System.out.println("fx = " + _fx);
//		String _sj = StringUtils.DateToStr(StringUtils.StrToDate(sj_,"yyyy/MM/dd hh:mm:ss"), "yyyyMMddHHmmss").substring(2);
//		String _sj = StringUtils.DateToStr(StringUtils.StrToDate(sj_,"yyyy/MM/dd hh:mm:ss"), "yyyyMMddHHmmss").substring(2);
		String _sj = StringUtils.DateToStr(new Date(System.currentTimeMillis()), "yyyyMMddHHmmss").substring(2);
		//String _sj = "20000000080000".substring(2);//模拟时间错误
		String info = _wd + _jd + _gc + _sd + _fx + _sj;

		String ss = s0 + id + s1 + info + s2;
		return ss;
	}
}
